package com.suyx.job.job;

import com.alibaba.fastjson.JSON;
import com.suyx.job.config.RedisUtils;
import com.suyx.job.entity.*;
import com.suyx.job.service.IDeviceService;
import com.suyx.job.service.IEmailService;
import com.suyx.job.service.IJobLogService;
import com.suyx.job.service.IRoleInfoService;
import com.suyx.job.utils.CommandUtils;
import com.suyx.job.utils.DateUtils;
import com.suyx.job.utils.EmailUtils;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.quartz.*;
import org.springframework.web.client.RestTemplate;

import static org.apache.commons.lang3.exception.ExceptionUtils.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: lanyanhua
 * @Date: 2018/10/17 0017 14:45
 * @Description:
 */
@Slf4j
public class ExecuteJob implements Job {

	public final static Map<String,String> deviceCode_map = new HashMap<>();
	static {   
		deviceCode_map.put("1", "0a2aa4710805");  
		deviceCode_map.put("2", "0e1b9c2a0006");
		deviceCode_map.put("3", "0ac2e8100905"); 
		deviceCode_map.put("4", "0f05fef90106");
		deviceCode_map.put("5", "c6c8060a7d28");
		deviceCode_map.put("6", "c338ccda7d28");
		deviceCode_map.put("7", "27676dce7d28");
		deviceCode_map.put("8", "c7b96ae87d29");
		deviceCode_map.put("9", "fc49d3c17d2a");
		deviceCode_map.put("10", "5740569e7d23");
		
		deviceCode_map.put("11", "f2b206bb7d2a");  
		deviceCode_map.put("12", "2766921f7d28");
		deviceCode_map.put("13", "c761d06a7d28"); 
		deviceCode_map.put("14", "c6f6c9857d28");
		deviceCode_map.put("15", "c309dc607d28");
		deviceCode_map.put("16", "fd269b987d2a");
		deviceCode_map.put("17", "f71a9a017d2a");
		deviceCode_map.put("18", "c7e2b20d7d29");
		deviceCode_map.put("19", "c752756f7d27");
		deviceCode_map.put("20", "c69ae4db7d29");
		
		deviceCode_map.put("21", "447 197");  
		deviceCode_map.put("22", "547 197");
		deviceCode_map.put("23", "c2ca5aac7d28"); 
		deviceCode_map.put("24", "447 300");
		deviceCode_map.put("25", "352061d57d28");
		deviceCode_map.put("26", "c391c13d7d28");
		deviceCode_map.put("27", "3be2d2547d29");
		deviceCode_map.put("28", "0dd6f0ef7d29");
		deviceCode_map.put("29", "c7d7e0da7d29");
		deviceCode_map.put("30", "3893d4a07d27");
		
		deviceCode_map.put("31", "c338be617d28");  
		deviceCode_map.put("32", "547 197");
		deviceCode_map.put("33", "884ad3e87d25"); 
		deviceCode_map.put("34", "447 300");
		deviceCode_map.put("35", "547 300");
		deviceCode_map.put("36", "647 300");
		deviceCode_map.put("37", "447 400");
		deviceCode_map.put("38", "547 400");
		deviceCode_map.put("39", "647 400");
	} 
	
    protected static RestTemplate restTemplate ;
    protected static IEmailService emailService ;
    protected static IJobLogService jobLogService;
    protected static EmailUtils emailUtils ;
    protected static IDeviceService deviceService ;
    protected static IRoleInfoService roleService ;
    protected static RedisUtils redisService;
    protected JobInfo jobInfo ;
    private int i = 0;
    

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("进入了---testJob : " + ++i);
        JobDataMap param = jobExecutionContext.getMergedJobDataMap();
        jobInfo = (JobInfo) param.get("jobInfo");
        String subject = "项目：" + jobInfo.getJobGroup() + ",执行任务：" + jobInfo.getJobName();
        JobLog jobLog = new JobLog(jobInfo);
        log.info("id:" + jobInfo.getJobId() + "," + subject);
        String introduce = jobInfo.getIntroduce();
        if(StringUtils.isNotEmpty(introduce)){
        	String[] deviceNos = introduce.split("a");
        	for(String s:deviceNos){
        		String cmd = "adb -s "+ deviceCode_map.get(s)  +" shell input swipe 455 940 455 747 200";
        		CommandUtils.excuteCommand(cmd);
        	}
        }
       /* Result result = executeCall();
        subject += result.getMessage();
        jobLog.end(result);*/
        
        /*try {
            jobLogService.save(jobLog);
        } catch (Exception e) {
            log.error(subject + "报错日志失败！！！" + getStackTrace(e));
        }
        try {
            if (isSend()) {
                EmailServerInfo emailServerInfo = emailService.findById(jobInfo.getEmailServerId()).get();
                EmailContent content = new EmailContent(subject, getEmailContent(jobLog));
                emailUtils.sendEmail(emailServerInfo, content);
            }
        } catch (Exception e) {
            log.error("发送邮箱报错！！" +  getStackTrace(e));
        }*/
        log.info("执行完成~");
    }

    /**
     * 初始化数据
     */
    public static void init(RestTemplate restTemplate,
    		IEmailService emailService,
    		IJobLogService jobLogService,
    		IDeviceService deviceService,
    		IRoleInfoService roleService,
    		RedisUtils redisService){
        ExecuteJob.emailService = emailService;
        ExecuteJob.emailUtils = new EmailUtils();
        ExecuteJob.jobLogService = jobLogService;
        ExecuteJob.restTemplate = restTemplate;
        ExecuteJob.deviceService = deviceService;
        ExecuteJob.roleService = roleService;
        ExecuteJob.redisService = redisService;
    }
    /**
     * 调用 定时任务url连接地址 负载均衡就重写这个方法
     */
    public Result executeCall(){
        try {
            Result result = restTemplate.getForObject(jobInfo.getExecuteAddress(), Result.class);
            if (result != null && result.isSuccess()) {
                log.info("执行成功：result" + JSON.toJSONString(result));
                return new Result(true,"200","执行成功！！");
            } else {
                log.error("执行失败：result:" + JSON.toJSONString(result));
                return new Result(false,"500","执行失败，请尽快处理！！！");
            }
        } catch (Exception e) {
            log.error( "执行时出现异常：" + getStackTrace(e));
            return new Result(false, "500", "执行时出现异常");
        }
    }

    /**
     * 是否发送 默认是存在邮箱就发送
     */
    public boolean isSend(){
        return jobInfo.getEmailServerId() != null;
    }

    /**
     *  邮箱发送内容
     */
    public String getEmailContent(JobLog jobLog){
        return "index:" + i +
                "执行地址：t" + jobLog.getExecuteAddress() + "\r\n" +
                "cron表达式：" + jobLog.getCronExpression() + "\r\n" +
                "开始执行时间：" + DateUtils.getStringDate("yyyy-MM-dd hh:mm:ss", jobLog.getStartTime()) + "\r\n" +
                "结束时间：" + DateUtils.getStringDate("yyyy-MM-dd hh:mm:ss", jobLog.getEndTime()) + "\r\n" +
                "执行结果：" + jobLog.isSuccess() + "\r\n" +
                "错误状态码：" + jobLog.getErrorCode() + "\r\n" +
                "消息：" + jobLog.getMessage() + "\r\n";
    }

}
